﻿using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel;

namespace LayeredArchitectureSample.Infrastructure.Services
{
    public class ServiceChannelFactory
    {
        public static ChannelFactory<TService> CreateDefault<TService>(string serviceEndpointAddress, Binding binding)
        {
            if (String.IsNullOrEmpty(serviceEndpointAddress))
                throw new ArgumentNullException("serviceEndpointAddress");

            if (binding == null)
                throw new ArgumentNullException("binding");

            var channelFactory = new ChannelFactory<TService>(binding, serviceEndpointAddress);

            channelFactory.Endpoint.Contract.Behaviors.Add(new ExceptionMarshallingBehavior());

            foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior =
                            op.Behaviors.Find<DataContractSerializerOperationBehavior>()
                            as DataContractSerializerOperationBehavior;

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            channelFactory.Open();

            return channelFactory;
        }
    }
}